from copy import deepcopy

from django.db import transaction
from rest_framework import serializers

from contract.log_util.db_log import create_change_log, create_addition_log, create_delete_log


class LogSerializer(serializers.ModelSerializer):
    @transaction.atomic()
    def create(self, validated_data):
        instance = super().create(validated_data)
        create_addition_log(self.context['request'].user.id, instance)
        return instance

    @transaction.atomic
    def update(self, instance, validated_data):
        origin_data = deepcopy(instance.__dict__)
        super().update(instance, validated_data)
        create_change_log(self.context['request'].user.id, instance, origin_data, instance.__dict__)
        return instance

    @transaction.atomic
    def delete(self, instance):
        create_delete_log(self.context['request'].user.id, instance)
        instance.delete()
